package ansi_escapes

import (
	"encoding/base64"
	"strconv"
)

var ESC = "\u001b["
var Beep = "\a"
var ClearScreen = "\x1bc"
var CursorGetPosition = "\x1b[6n"
var CursorHide = "\x1b[?25l"
var CursorLeft = "\x1b[1000D"
var CursorNextLine = "\x1b[E"
var CursorPrevLine = "\x1b[F"
var CursorRestorePosition = "\x1b[u"
var CursorSavePosition = "\x1b[s"
var CursorShow = "\x1b[?25h"
var EraseDown = "\x1b[J"
var EraseEndLine = "\x1b[K"
var EraseLine = "\x1b[2K"
var EraseScreen = "\x1b[2J"
var EraseStartLine = "\x1b[1K"
var EraseUp = "\x1b[1J"
var ScrollDown = "\x1b[T"
var ScrollUp = "\x1b[S"

func CursorToXY(x, y int) string {
	return ESC + strconv.Itoa(y+1) + ";" + strconv.Itoa(x+1) + "H"
}

func CursorToX(x int) string {
	return ESC + strconv.Itoa(x+1) + "G"
}

func CursorTo() string {
	return ESC + "H"
}
func CursorMove(x, y int) string {
	ret := ""
	if x < 0 {
		ret += ESC + strconv.Itoa(-x) + "D"
	} else if x > 0 {
		ret += ESC + strconv.Itoa(x) + "C"
	}
	if y < 0 {
		ret += ESC + strconv.Itoa(-y) + "A"
	} else if y > 0 {
		ret += ESC + strconv.Itoa(y) + "B"
	}
	return ret
}

func CursorUp(count int) string {
	return ESC + strconv.Itoa(count) + "A"
}
func CursorDown(count int) string {
	return ESC + strconv.Itoa(count) + "B"
}

func CursorForward(count int) string {
	return ESC + strconv.Itoa(count) + "C"
}

func CursorBackward(count int) string {
	return ESC + strconv.Itoa(count) + "D"
}

func EraseLines(count int) string {
	clear := ""
	for i := 0; i < count; i++ {
		clear += CursorLeft + EraseEndLine
		if i < count-1 {
			clear += CursorUp(1)
		}
	}
	return clear
}

type ImageOpts struct {
	Width               int
	Height              int
	PreserveAspectRatio bool
}

func Image(buf []byte, opts *ImageOpts) string {
	ret := "\u001b]1337;File=inline=1"
	if opts != nil {
		if opts.Width != 0 {
			ret += ";width=" + strconv.Itoa(opts.Width)
		}
		if opts.Height != 0 {
			ret += ";height=" + strconv.Itoa(opts.Height)
		}
		if opts.PreserveAspectRatio == false {
			ret += ";preserveAspectRatio=0"
		}
	}
	return ret + ":" + base64.StdEncoding.EncodeToString(buf) + "\u0007"
}

func ITermSetCwd(cwd string) string {
	return "\u001b]50;CurrentDir=" + cwd + "\u0007"
}
